from django.shortcuts import render
from django.http import HttpResponse,Http404,JsonResponse

from myadmin.models import Users,Types,Goods,Cart,Address,Order,OrderInfo

# Create your views here.

#前台首页
def index(request):
    #获取所有二级菜单
    obs = Types.objects.exclude(id=0)
    #获取一级分类
    tys = Types.objects.filter(pid=0)

    for x in tys:
        x.sub = Types.objects.filter(pid=x.id)




    con = {"ulist":obs,'xlist':tys}

    return render(request,'home/index.html',con)
#列表页
def lists(request,tid):

    #接收分类id,获取对象
    ob = Types.objects.get(id=tid)

    data = {}

    #判断是几级分类

    if ob.pid == 0:

        data['parent'] = ob 

        #获取子类
        data['typelists'] = Types.objects.filter(pid=ob.id)

        #获取商品

        data['goodslists'] = Goods.objects.filter(tid__in=data['typelists'])

    else:
        data['parent'] = Types.objects.get(id=ob.pid)

        typelists = Types.objects.filter(pid=data['parent'].id)

        #作高亮处理
        for x in typelists:
            if x.id == ob.id:
                x.selected = True
        data['typelists'] = typelists

        #获取商品

        data['goodslists'] = Goods.objects.filter(tid = ob.id)





    obs = Types.objects.exclude(id=0)

    con = {"ulist":obs,'data':data}
    return render(request,'home/list.html',con)

#详情页
def info(request,gid):

    # 根据商品id,获取商品信息
    try:
        ob = Goods.objects.get(id=gid)
        ob.clicknum += 1
        ob.save()
        # 获取所有的二级菜单
        obs = Types.objects.exclude(pid = 0)
        # 分配数据
        context = {'ulist':obs,'ginfo':ob}
        return render(request,'home/info.html',context)
    except:
        # pass
        # 报404
        raise Http404("纳尼,怎么不见了?")


#注册页
def register(request):

    #判断请求方式

    if request.method == 'GET':

        return render(request,'home/register.html')
    if request.method == 'POST':
        data = request.POST.dict()

        del data['csrfmiddlewaretoken']

        # 验证手机号和验证码是否正确
        if data['phone'] == request.session['yzm']['phone'] and data['code'] == request.session['yzm']['code']:
        #进行密码加密
            from django.contrib.auth.hashers import make_password, check_password
            data['password'] = make_password(data['password'],None,'pbkdf2_sha256')
            try:
                # 执行注册
                del data['code']
                ob = Users.objects.create(**data)
                return HttpResponse('<script>alert("注册成功,请登录");location.href="/login/"</script>')

            except:
                return HttpResponse('<script>alert("注册失败");location.href="/register/"</script>')
        else:
            return HttpResponse('<script>alert("验证码错误");location.href="/register/"</script>')
#登录页
def login(request):

    npath = request.GET.get('next','/')

    #判断请求方式

    if request.method == 'GET':



        return render(request,'home/login.html')
    if request.method == 'POST':

         # 获取数据
        data = request.POST.dict()
        del data['csrfmiddlewaretoken']

        

        #判断用户是否存在
        try:
            ob = Users.objects.get(phone=data['phone'])
            
            #判断密码
            from django.contrib.auth.hashers import check_password

            if check_password(data['password'],ob.password):
                #存入session
                request.session['vipuser'] = {'uid':ob.id,'uname':ob.username,'phone':ob.phone,'pic':ob.pic}
                print(request.session['vipuser'])

                return HttpResponse('<script>alert("登录成功");location.href="'+npath+'"</script>')


        except:
            pass

        return HttpResponse('<script>alert("用户名或密码错误");history.back(-1);</script>')



#退出登录

def logout(request):

    #获取路径

    npath = request.GET.get('next','/')

    request.session['vipuser'] = ''

    return HttpResponse('<script>alert("退出登录成功");location.href="'+npath+'" </script>')




#个人信息
def myindex(request,mid):


    return render(request,'home/myindex.html')
#修改个人信息
def myindexedit(request,mid):
    ob = Users.objects.get(id=mid)
    if request.method == 'GET':
        con = {'ul':ob}
        return render(request,'home/myindexedit.html',con)

    elif request.method == 'POST':
        ob.username = request.POST['username']
        ob.email = request.POST['email']
        ob.phone = request.POST['phone']
        ob.age = request.POST['age']
        data = request.session['vipuser']
        data['uname'] = ob.username
        request.session['vipuser'] = data
        ob.save()

        return HttpResponse('<script>alert("修改信息成功");location.href="/myindex/'+ str(ob.id)+'" </script>')




    
#购物车添加
def cartadd(request):
    try:
        #定义空字典用来用户id 商品id 商品数量
        data = {}
        print(data)
        data['uid'] = Users.objects.get(id=request.session['vipuser']['uid'])

        data['gid'] = Goods.objects.get(id=request.GET.get('gid'))

        data['num'] = request.GET.get('num')

        #判断数据库里是否已经有了该商品、
        res = Cart.objects.filter(uid=data['uid']).filter(gid=data['gid'])



        if res:
            #说明已经有了商品
            res[0].num += int(data['num'])
            res[0].save()
        else:
            ob = Cart.objects.create(**data)

        return JsonResponse({'code':0,'msg':'添加购物车成功'})
    except:
        return JsonResponse({'code':1,'msg':'添加购物车失败'})

#购物车页面
def cartindex(request):
    #获取用户购物车信息
    data = Cart.objects.filter(uid=request.session['vipuser']['uid'])

    #分配数据

    con = {'clist':data,'ulist':Types.objects.exclude(id=0)}

    return render(request,'home/cindex.html',con)


#购物车修改

def cartedit(request):
    # 获取参数
    gid = request.GET['gid']
    num = request.GET['num']

    #获取购物车对象
    try:

        obs = Cart.objects.filter(uid=request.session['vipuser']['uid']).filter(gid=gid)[0]
        obs.num = int(num)
        obs.save()
        return JsonResponse({'code':0,'msg':'购物车数量更新成功'})
    except:
        return JsonResponse({'code':1,'msg':'购物车数量更新失败'})


# 购物车删除

def cartdel(request):
    
    # 获取id

    sid = request.GET['sid']

    ob = Cart.objects.get(id=sid)
    ob.delete()

    return JsonResponse({'code':0,'msg':'购物车更新成功'})


#清空购物车
def cartsdel(request):
    
    ob = Cart.objects.all()
    ob.delete()
    return HttpResponse('<script>alert("清空购物车成功");location.href="/cart/index/" </script>')


#确认订单
def confirmorder(request):
    ids = eval(request.GET['ids'])
    obs = Cart.objects.filter(id__in=ids)

    #分配数据
    con = {'clist':obs}



    return render(request,'home/confirmorder.html',con)
    


# 添加新地址
def addressinsert(request):
    # 接受参数
    data = request.POST.dict()
    ids = data['ids']
    del data['csrfmiddlewaretoken']
    del data['ids']

    # 获取用户对象
    data['uid'] = Users.objects.get(id=request.session['vipuser']['uid'])
    # 执行地址添加
    ob = Address.objects.create(**data)


    return HttpResponse('<script>location.href="/confirm/order/?ids='+ids+'"</script>')

# 设置默认地址
def addressset(request):
    # 接受id,获取用户id,在修改
    aid = request.GET['aid']
    uid = request.session['vipuser']['uid']

    # 先获取当前用户的所有地址
    obs = Address.objects.filter(uid=uid)
    obs.update(isSelect=0)
    ob = obs.get(id=aid)
    ob.isSelect = True
    ob.save()

    return HttpResponse('addressset')
#订单提交
def orderinsert(request):
    data = request.POST.dict()
    print(data)

    #计算总价
    tprice = 0
    for x in eval(data['ids']):
        cart = Cart.objects.get(id=x)
        tprice += cart.gid.price * cart.num

    #创建订单
    ob = Order()
    ob.totalprice = tprice
    ob.status = 1

    ob.addressid = Address.objects.get(id=data['addressid'])
    ob.uid = Users.objects.get(id=request.session['vipuser']['uid'])
    ob.save()




    #创建订单详情
    for x in eval(data['ids']):
        cart = Cart.objects.get(id=x)
        obo = OrderInfo()
        obo.orderid = ob
        obo.goodsid = cart.gid
        obo.num = cart.num
        obo.price = cart.gid.price
        obo.save()
        #在购物车中删除已购买的商品
        cart.delete()
        
    return HttpResponse('<script>alert("您已提交订单，请付款");location.href="/order/buy/'+str(ob.id)+'/"</script>')

#订单页面
def buy(request,bid):


    #查询对应的数据
    ob = Order.objects.get(id=bid)
    #分配数据
    con = {'blist':ob}

    #加载模板
    return render(request,'home/buy.html',con)


#我的订单
def myorders(request):
    
    #查询当前用户的订单信息
    ob = Order.objects.filter(uid=request.session['vipuser']['uid'])

    con = {'myorders':ob}

    return render(request,'home/myorders.html',con)


#短信测试

def sendsms(request):

    from dysms import demo_sms_send
    import random

    #获取手机号
    phone = request.GET['phone']

    code = random.randrange(1000,9999)

    print(phone,code)

    #存入session
    request.session['yzm'] = {'phone':phone,'code':str(code)}

    #执行验证码发送

    res = demo_sms_send.send(str(code),phone)
    res = eval(res)

    if res['Code'] == 'OK':
        # 发送成功
        return JsonResponse({'code':0,'msg':'发送成功'})
    else:
        # 发送失败
        return JsonResponse({'code':1,'msg':'发送失败','error':res['Message']})
    

